/*
 * SurfaceUtils.cpp
 *
 *  Created on: Apr 15, 2012
 *      Author: gonzalo
 */

#include "SurfaceUtils.h"
#include "math.h"
#include "../lib/SDL_rotozoom.h"

bool SurfaceUtils::overlaps(SDL_Surface surface1,SDL_Surface surface2){

	bool isSurface1Origen =false;


	if(surface1.clip_rect.x < 0) surface1.clip_rect.x =0;
	if(surface1.clip_rect.y < 0) surface1.clip_rect.y =0;
	if(surface2.clip_rect.x < 0) surface2.clip_rect.x =0;
	if(surface2.clip_rect.y < 0) surface2.clip_rect.y =0;


	int xOrigin = 0;
	int yOrigin = 0;
	//Traslado ambos rectangulos
	//Tomo como cero al que esta mas cerca del origen.

	//Calculo el modulo, para evitar valores negativos
	float mod1 = sqrt(pow(surface1.clip_rect.x,2) + pow(surface1.clip_rect.y,2));
	float mod2 = sqrt(pow(surface2.clip_rect.x,2) + pow(surface2.clip_rect.y,2));

	if(mod2 > mod1  || mod1 == mod2){
		xOrigin = surface1.clip_rect.x;
		yOrigin = surface1.clip_rect.y;
		isSurface1Origen =true;
	}else{
		xOrigin = surface2.clip_rect.x;
		yOrigin = surface2.clip_rect.y;
		isSurface1Origen =false;
	}

	//Muevo ambas superficies al origine
	surface1.clip_rect.x -= xOrigin;
	surface1.clip_rect.y -= yOrigin;

	surface2.clip_rect.x -= xOrigin;
	surface2.clip_rect.y -= yOrigin;


	if(surface1.clip_rect.x < 0) surface1.clip_rect.x =0;
	if(surface1.clip_rect.y < 0) surface1.clip_rect.y =0;
	if(surface2.clip_rect.x < 0) surface2.clip_rect.x =0;
	if(surface2.clip_rect.y < 0) surface2.clip_rect.y =0;


	//Calculo el modulo


	float pos1;
	float pos2;
	if(isSurface1Origen){
		pos1= sqrt(pow(surface1.clip_rect.h,2) + pow(surface1.clip_rect.w,2));
		pos2= sqrt(pow(surface2.clip_rect.x,2) + pow(surface2.clip_rect.y,2));


		if(pos1 > pos2){
			//Hay contacto
			return true;
		}

	}else{
		pos1= sqrt(pow(surface1.clip_rect.x,2) + pow(surface1.clip_rect.y,2));
		pos2= sqrt(pow(surface2.clip_rect.h,2) + pow(surface2.clip_rect.w,2));

		if(pos2 > pos1){
			//Hay contacto
			return true;
		}
	}

	return false;
}



SDL_Surface* SurfaceUtils::resizeSurface(float newWidth, float newHeigth, SDL_Surface* originalSurface){
	SDL_Surface* resizedSurface=NULL;

	if(originalSurface == NULL)
		return NULL;

    float width_image=(float)(originalSurface->w);
    float heigth_image=(float)(originalSurface->h);

    float zoomX = (newWidth/width_image);
    float zoomY = (newHeigth/heigth_image);

	return resizedSurface = rotozoomSurfaceXY(originalSurface,0,zoomX,zoomY,0);
}
